import * as mockjs from "mockjs";
import * as cryptoJS from 'crypto-js';
import moment from "moment";
import { history } from "@umijs/max";
import { stringify } from 'querystring';
import environment from "@/environment";

const IHelper = new class {
  hash(len?: number, option?: {mixed?: boolean}): string {
    const length: number = len ? len : 6
    const lower: string = "abcdefghighlmnopqrstuvwxyz"
    const upper: string = lower.toUpperCase()
    const number: string = "0123456789"
    const symbol: string = "!@?$%^&*"
    const pool: string = `${number}${upper}${lower}${option?.mixed ? symbol : ""}`
    return mockjs.Random.string(lower, 1) + mockjs.Random.string(pool, length - 1)
  }

  md5(l: string): string {
    return cryptoJS.MD5(l).toString()
  }

  unix(): number {
    return moment().unix()
  }

  convertToQueryString(params: {[prop: string]: any}): string {
    return Object.keys(params).map(k => `${k}=${encodeURIComponent(params[k])}`).join("&")
  }

  timeFormatted(format?: string) {
    return moment().format(format || "YYYY-MM-DD HH:mm:ss")
  }

  getArray(len: number): number[] {
    return Array.from(new Array(len).keys())
  }

  linkToLogin(replace?: boolean) {
    const { search, pathname } = window.location;
    const navFunc = replace ? history.replace : history.push
    const navOptions = {
      pathname: '/user/login',
      search: stringify({
        redirect: pathname + search,
      }),
    }
    navFunc.call(history, navOptions)
  }
  getServerAsset(assetPath: string): string {
    return `${environment.assetDomain}${assetPath}`
  }
}

export default IHelper
